var {
  randomUtils,
  textUtils,
  timeUtils,
  clickUtils,
  ocrUtils,
  fmtUtils,
  appUtils,
  logUtils,
  clickContent,
} = require("../../utils/index");
var adCommon = require("../adCommon");
module.exports = {
  watchAd(span, handleNextAd) {
    this.appName = "悟空浏览器";
    this.span = span;
    this.handleNextAd = handleNextAd;
    var startTime = Date.now();
    var count = 0;
    var hasCheckFuDai = false;
    adCommon.adCount++;
    logUtils.info("第", adCommon.adCount, "/", adCommon.maxAdCount, "个广告");
    while (true) {
      count++;
      var hasExec = timeUtils.hasExec(startTime);
      if (count % 5 == 0) {
        logUtils.info("已经观看", hasExec, "/", this.span);
      }
      if (!hasCheckFuDai) {
        if (this.checkFuDai()) {
          hasCheckFuDai = true;
          this.span = this.span + 20;
        }
      }
      if (count >= 4 && this.isOver()) {
        this.stopAd();
        break;
      }
      if (hasExec > this.span) {
        if (count % 5 != 0) {
          logUtils.info("已经观看", hasExec, "/", this.span, "将执行关闭广告");
        }
        this.stopAd();
        break;
      }
      sleep(2 * 1000);
    }
  },
  stopAd() {
    for (var index = 0; index < 5; index++) {
      var content = "跳过";
      if (clickContent(content)) {
        sleep(randomUtils.getRandom(3, 5, 1000));
      } else {
        return true;
      }
    }
  },
  inAd() {
    var contents = [
      //prettier-disable
      "反馈",
      "广告",
    ];
    var TextUI = textUtils.existsOneTextStartsWith(contents);
    if (TextUI) {
      return TextUI;
    }
    var TextOCR = ocrUtils.captureExistsOneText(contents);
    if (TextOCR) {
      return TextOCR;
    }
    return false;
  },
  isOver() {
    var contents = ["领取成功", "跳过"];
    var TextOCR = ocrUtils.captureExistsOneText(contents);
    if (TextOCR) {
      return true;
    }
    sleep(10 * 1000);
    var TextUI = textUtils.existsOneTextStartsWith(contents);
    if (TextUI) {
      return true;
    }
    return false;
  },
  checkFuDai() {
    var content = "点击福袋";
    if (clickContent(content)) {
      sleep(randomUtils.getRandom(3, 5, 1000));
      return true;
    }
    return false;
  },
};
